from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import SKUImage, SKU
from apps.meiduo_admin.serializers.image_serializer import ImageSerializer, SKUSerializer
from apps.meiduo_admin.utils import PageNum


# 获取图片列表
class ImageView(ModelViewSet):
    # 图片序列化器
    serializer_class = ImageSerializer
    # 图片查询集
    queryset = SKUImage.objects.all()
    # 分页
    pagination_class = PageNum

    # 重写拓展类的保存业务逻辑
    def create(self, request, *args, **kwargs):
        # 获取sku_id
        sku_id = request.data.get('sku')
        # 获取前段传递的image文件
        image = request.FILES.get("image")
        # 把图片上传到fastdfs里返回一个图片地址
        from fdfs_client.client import Fdfs_client
        # 创建FastDFS连接对象
        client = Fdfs_client('utils/fastdfs/client.conf')
        # 上传图片到fastDFS
        res = client.upload_by_buffer(image.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return Response(status=403)
        # 获取上传后的路径
        image_url = res['Remote file_id']
        # 保存图片
        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)
        # 返回结果
        return Response({
            'id': img.id,
            'sku': sku_id,
            'image': img.image.url
        },
            # 前端需要接受201状态
            status=201
        )

    # 重写拓展类的更新业务逻辑
    def update(self, request, *args, **kwargs):
        # 获取sku_id
        sku_id = request.data.get('sku')
        # 获取前端传递的image文件
        image = request.FILES.get('image')
        # 获取要修改的模型类对象的id
        pk = kwargs.get('pk')
        # 把图片上传到fastdfs里 返回一个图片地址
        from fdfs_client.client import Fdfs_client
        # 创建FastDFS连接对象
        client = Fdfs_client('utils/fastdfs/client.conf')
        # 上传图片到fastdfs
        result = client.upload_by_buffer(image.read())
        # 判断是否上传成功
        if result['Status'] != 'Upload successed.':
            return Response(status=403)
        # 取出在fastdfs里的地址 把这地址保存到数据库
        file_id = result.get('Remote file_id')
        # 获取要修改的地址
        sku_image = SKUImage.objects.get(id=pk)
        # 把图片的地址补充上
        sku_image.image = file_id
        # 保存数据
        sku_image.save()
        # 返回响应
        return Response(status=status.HTTP_201_CREATED)


# 获取商品列表的id
class SKUView(APIView):
    def get(self, request):
        data = SKU.objects.all()
        ser = SKUSerializer(data, many=True)
        return Response(ser.data)
